import 'dart:io';
import 'dart:typed_data';

import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:gcode_printer/utils/filter_color_util.dart';
import 'package:image/image.dart' as img;
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:share/share.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String? title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Image? _image;
  img.Image? _des;
  String _gcode = '';

  void _incrementCounter() async {
    final ImagePicker _picker = ImagePicker();
    // Pick an image
    final XFile? xFile = await _picker.pickImage(source: ImageSource.gallery);
    if (xFile == null) {
      return;
    }

    Uint8List bytes =
        await xFile.readAsBytes(); // the method toByteData here is not pop up.
    img.Image? image = img.decodeImage(bytes);
    if (image == null) {
      return;
    }

    img.Image thumbnail = img.copyResize(image, width: 210, height: 210);
    _des = FilterColorUtil.filterColor(thumbnail, FilterType.blackWhite);

    var encodePng = img.encodePng(_des!) as Uint8List;
    _image = Image.memory(encodePng, width: 210, height: 210);

    _gcode='';
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      body: SingleChildScrollView(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            SizedBox(height: 20),
            if (_image != null) _image!,
            TextButton(
                onPressed: () {
                  _incrementCounter();
                },
                child: Text('选择图片')),
            TextButton(
                onPressed: () {
                  _genGcode();
                },
                child: Text('生成Gcode')),
            if(_gcode.isNotEmpty)
            TextButton(
                onPressed: () {
                  _write(_gcode);
                },
                child: Text('导出文件')),
            Text(_gcode)
          ],
        ),
      ),
      // floatingActionButton: FloatingActionButton(
      //   onPressed: _incrementCounter,
      //   tooltip: 'Increment',
      //   child: Icon(Icons.add),
      // ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  void _genGcode() {
    if (_des == null) {
      return;
    }
    double density = 7;
    double w = 30;
    double h = 30;

    final buffer = StringBuffer();
    String heard=''';Header Start
;renderMethod: point
;file_total_lines: 42543
;estimated_time(s): 504.20160000000004
;MAXX: 30
;MAXY: 30
;MAXZ: 0
;MINX: 0
;MINY: 0
;MINZ: 0
;work_speed(mm/minute): 1000
;jog_speed(mm/minute): 1500
;power(%): 1000
;Header End

''';
    // buffer.write(heard);
    buffer.write('G90 (use absolute coordinates)\nG1 F1000\nM4 ');
    Uint8List bytes = _des!.getBytes();
    List<String> list=[];
    for (int i = 0, len = bytes.length; i < len; i += 4) {
      int step = i ~/ 4;
      int row = step ~/ 210;
      int col = step % 210;
      String text;
      if(col==0) {
        String x=(row/density).toStringAsFixed(3);
        String y;
        if(row%2==0) {
          y = (30 - col / density).toStringAsFixed(3);
        }else{
          y=(col/density).toStringAsFixed(3);
        }
        // text = 'G1 X${row * 1000 ~/ density / 1000} Y${30 -
        //     col * 1000 ~/ density / 1000} S${255 == bytes[i] ? 1000 : 0}\n';
        text = 'S0\nG0 X${x} Y${y} S0\nG1 Y${y} S${255 == bytes[i] ? 0 : 1000}\n';
        list.add(text);
      }else{
        String y=(30-col/density).toStringAsFixed(3);
        text = 'Y${y} S${255==bytes[i]?0:1000}\n';
        if(row%2==0){
          list.add(text);
        }else{
          list.insert(1, text);
        }
      }
      if(col==209){
        buffer.writeAll(list);
        list.clear();
      }
    }
    String end='''
S0
M5
G0 X30.000 Y30.000 Z0.000
G28''';
    buffer.write(end);
    _gcode = buffer.toString();
    print(_gcode);
    setState(() {});
  }

  _write(String text) async {
    final isGranted = await Permission.storage.request().isGranted;
    if (!isGranted) {
      return;
    }

    await DirectoryUtil.getInstance();
    await DirectoryUtil.createTempDir(category: 'Download');
    final String? path = DirectoryUtil.getTempPath(fileName: '${DateTime.now().microsecondsSinceEpoch}', category: 'Download', format: 'gcode');
    print(path);

    File file = File(path!);
    // file.writeAsBytesSync(img.encodePng(_des!));

    await file.writeAsString(text);

    Share.shareFiles([path], text: 'Great GCode');
  }
}
